package com.risk.management.service.impl;

import com.risk.management.entity.Risk;
import com.risk.management.mapper.RiskMapper;
import com.risk.management.service.RiskHistoryService;
import com.risk.management.service.RiskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 风险服务实现类
 */
@Service
public class RiskServiceImpl implements RiskService {

    @Autowired
    private RiskMapper riskMapper;
    
    @Autowired
    private RiskHistoryService riskHistoryService;

    @Override
    public Risk getRiskById(Long id) {
        return riskMapper.selectById(id);
    }

    @Override
    public List<Risk> getAllRisks() {
        return riskMapper.selectAll();
    }

    @Override
    public List<Risk> getRisksByProjectId(Long projectId) {
        return riskMapper.selectByProjectId(projectId);
    }

    @Override
    public List<Risk> getRisksByOwnerId(Long ownerId) {
        return riskMapper.selectByOwnerId(ownerId);
    }

    @Override
    public List<Risk> getRisksByProposerId(Long proposerId) {
        return riskMapper.selectByProposerId(proposerId);
    }

    @Override
    public List<Risk> getRisksByStatus(Integer status) {
        return riskMapper.selectByStatus(status);
    }

    @Override
    public List<Risk> getRisksByLevel(Integer level) {
        return riskMapper.selectByLevel(level);
    }

    @Override
    public List<Risk> getRisksByProjectIdAndStatus(Long projectId, Integer status) {
        return riskMapper.selectByProjectIdAndStatus(projectId, status);
    }

    @Override
    @Transactional
    public boolean addRisk(Risk risk) {
        // 设置创建和更新时间
        Date now = new Date();
        risk.setCreateTime(now);
        risk.setUpdateTime(now);
        
        // 如果状态为空，设置为已识别状态
        if (risk.getStatus() == null) {
            risk.setStatus(1); // 1表示已识别
        }
        
        // 如果级别为空，计算风险级别
        if (risk.getLevel() == null && risk.getProbability() != null && risk.getImpact() != null) {
            risk.setLevel(calculateRiskLevel(risk.getProbability(), risk.getImpact()));
        }
        
        boolean success = riskMapper.insert(risk) > 0;
        
        // 记录历史
        if (success) {
            riskHistoryService.recordCreate(risk, risk.getProposerId(), "系统");
        }
        
        return success;
    }

    @Override
    @Transactional
    public boolean updateRisk(Risk risk) {
        // 检查风险是否存在
        Risk existingRisk = getRiskById(risk.getId());
        if (existingRisk == null) {
            return false;
        }
        
        // 设置更新时间
        risk.setUpdateTime(new Date());
        
        // 如果级别为空，计算风险级别
        if (risk.getLevel() == null && risk.getProbability() != null && risk.getImpact() != null) {
            risk.setLevel(calculateRiskLevel(risk.getProbability(), risk.getImpact()));
        }
        
        boolean success = riskMapper.update(risk) > 0;
        
        // 记录历史
        if (success) {
            // 如果状态有变化
            if (risk.getStatus() != null && !risk.getStatus().equals(existingRisk.getStatus())) {
                riskHistoryService.recordStatusUpdate(risk, existingRisk.getStatus(), risk.getStatus(), 
                                                    risk.getProposerId(), "系统", "更新风险状态");
            }
            
            // 如果责任人有变化
            if (risk.getOwnerId() != null && !risk.getOwnerId().equals(existingRisk.getOwnerId())) {
                riskHistoryService.recordOwnerUpdate(risk, existingRisk.getOwnerId(), risk.getOwnerId(), 
                                                   risk.getProposerId(), "系统", "更新风险责任人");
            }
            
            // 如果风险级别有变化
            if (risk.getLevel() != null && !risk.getLevel().equals(existingRisk.getLevel())) {
                riskHistoryService.recordLevelUpdate(risk, existingRisk.getLevel(), risk.getLevel(), 
                                                   risk.getProposerId(), "系统", "更新风险级别");
            }
        }
        
        return success;
    }

    @Override
    @Transactional
    public boolean deleteRisk(Long id) {
        // 检查风险是否存在
        Risk risk = getRiskById(id);
        if (risk == null) {
            return false;
        }
        
        boolean success = riskMapper.deleteById(id) > 0;
        
        // 记录历史
        if (success) {
            riskHistoryService.recordDelete(risk, risk.getProposerId(), "系统", "删除风险");
        }
        
        return success;
    }

    @Override
    @Transactional
    public boolean updateRiskStatus(Long id, Integer status) {
        // 检查风险是否存在
        Risk risk = getRiskById(id);
        if (risk == null) {
            return false;
        }
        
        // 检查状态是否有效（1-已识别，2-已分析，3-已计划，4-已处理，5-已解决）
        if (status < 1 || status > 5) {
            return false;
        }
        
        Integer beforeStatus = risk.getStatus();
        boolean success = riskMapper.updateStatus(id, status) > 0;
        
        // 记录历史
        if (success) {
            // 更新risk对象的状态，用于历史记录
            risk.setStatus(status);
            riskHistoryService.recordStatusUpdate(risk, beforeStatus, status, 
                                                risk.getProposerId(), "系统", "更新风险状态");
        }
        
        return success;
    }

    @Override
    @Transactional
    public boolean updateRiskOwner(Long id, Long ownerId) {
        // 检查风险是否存在
        Risk risk = getRiskById(id);
        if (risk == null) {
            return false;
        }
        
        Long beforeOwnerId = risk.getOwnerId();
        boolean success = riskMapper.updateOwner(id, ownerId) > 0;
        
        // 记录历史
        if (success) {
            // 更新risk对象的责任人，用于历史记录
            risk.setOwnerId(ownerId);
            riskHistoryService.recordOwnerUpdate(risk, beforeOwnerId, ownerId, 
                                               risk.getProposerId(), "系统", "更新风险责任人");
        }
        
        return success;
    }

    @Override
    public int calculateRiskLevel(int probability, int impact) {
        // 计算风险等级
        // probability和impact的值范围都是1-3（1-低，2-中，3-高）
        int riskScore = probability * impact;
        
        // 根据风险分数确定风险等级
        // 1-2: 低风险
        // 3-4: 中风险
        // 6-9: 高风险
        if (riskScore <= 2) {
            return 1; // 低风险
        } else if (riskScore <= 4) {
            return 2; // 中风险
        } else {
            return 3; // 高风险
        }
    }
} 